package org.uim.cricket.entities.parser.filters.impl;

import org.uim.cricket.entities.FullGround;
import org.uim.cricket.entities.parser.filters.GroundDetailFilterable;

public class DefaultGroundDetailFilter implements GroundDetailFilterable {

	@Override
	public void filterGroundAttribute(FullGround ground, String attrKey, String attrValue) {
		if (attrKey == null || attrValue == null) return;
		if (attrKey.equalsIgnoreCase("Capacity")) {
			int pos = attrValue.indexOf(' ');
			if (pos > 0) {
				attrValue = attrValue.substring(0, pos).trim();
			}
			ground.addNewAttribute("Capacity", attrValue);
		} else if (attrKey.equalsIgnoreCase("Current local time")) {
			int epos = attrValue.lastIndexOf(')');
			int spos = attrValue.lastIndexOf('(');
			if (spos < epos && spos > 0) {
				String utc = attrValue.substring(spos+1, epos).trim();
				int pos = utc.indexOf(' ');
				if (pos >= 0) utc=utc.substring(pos+1);
				ground.addNewAttribute("Time Difference", utc);
			}
		} else if (attrKey.toLowerCase().startsWith("home team")) {
			String[] teams = attrValue.split("[,]");
			for (int i=0;i<teams.length;i++) {
				ground.addNewHomeTeam(teams[i].trim());
			}
		} else if (attrKey.equalsIgnoreCase("End names")) {
			String[] ends = attrValue.split("[,]");
			if (ends.length == 2) {
				ground.addNewAttribute("End Name 1", ends[0].trim());
				ground.addNewAttribute("End Name 2", ends[1].trim());
			}
		} else if (attrKey.equalsIgnoreCase("Playing area")) {
			String[] wh = attrValue.split("[,]");
			if (wh.length == 2) {
				
				double l = this.captureLength(wh[0]);
				double w = this.captureLength(wh[1]);
				if (l>0 && w > 0) {
					if (wh[0].indexOf("yd ") > 0) l*=0.9144;
					if (wh[1].indexOf("yd ")>0) w*=0.9144;
					ground.addNewAttribute("Length", Math.round(l) + "");
					ground.addNewAttribute("Width", Math.round(w)+"");
				}
			}
		} else {
			ground.addNewAttribute(attrKey, attrValue);
		}
	}

	private double captureLength(String val) {
		StringBuilder s = new StringBuilder();
		for (int i=0;i<val.length();i++) {
			if (val.charAt(i)>='0' && val.charAt(i)<='9') s.append(val.charAt(i));
			if (val.charAt(i)=='.') s.append('.');
			else break;
		}
		if (s.length() > 0) {
			return Double.parseDouble(s.toString());
		} 
		return -1.0;
	}
	
}
